package com.ethannhu.todaynews.component.main

import android.util.Log
import androidx.lifecycle.viewModelScope
import com.bumptech.glide.Glide
import com.bumptech.glide.request.FutureTarget
import com.ethannhu.repository.DefaultNetworkRepository
import com.ethannhu.superui.util.SuperNetworkUtil
import com.ethannhu.todaynews.AppContext
import com.ethannhu.todaynews.R
import com.ethannhu.todaynews.component.ad.Ad
import com.ethannhu.todaynews.component.user.User
import com.ethannhu.todaynews.entity.response.onSuccess
import com.ethannhu.todaynews.model.BaseViewModel
import com.ethannhu.todaynews.util.FileUtil
import com.ethannhu.todaynews.util.PreferenceUtil
import com.ethannhu.todaynews.util.ResourceUtil
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import org.apache.commons.collections4.CollectionUtils
import org.apache.commons.io.FileUtils
import java.io.File

/**
 * 首页 VM
 */
class MainViewModel : BaseViewModel() {
    private val _userData = MutableSharedFlow<User>()
    val userData: Flow<User> = _userData

    fun loadUserData() {
        viewModelScope.launch(coroutineExceptionHandler) {
            DefaultNetworkRepository.userDetail(PreferenceUtil.getUserId()).onSuccess(viewModel) {
                _userData.emit(it!!)
            }
        }
    }

    fun loadSplashAd() {
        viewModelScope.launch(coroutineExceptionHandler) {
            DefaultNetworkRepository.ads(style = 0).onSuccess(viewModel) {
                if (CollectionUtils.isNotEmpty(it.data)) {
                    downloadAd(it.data!!.first())
                } else {
                    //删除本地广告数据
                    deleteSplashAd()
                }
            }
        }
    }

    private fun deleteSplashAd() {
        //获取广告信息
        val ad = PreferenceUtil.getSplashAd()

        ad?.let {
            //删除配置文件
            PreferenceUtil.setSplashAd(null)

            //删除文件
            FileUtils.deleteQuietly(FileUtil.adFile(AppContext.instance, ad.icon!!))
        }
    }

    private suspend fun downloadAd(data: Ad) {

        //判断文件是否存在，如果存在就不下载
        val targetFile: File = FileUtil.adFile(AppContext.instance, data.icon!!)
        Log.d("hu", "downloadAd:${targetFile.absolutePath}")
        if (targetFile.exists()) {
            PreferenceUtil.setSplashAd(data)
            return
        }

        try {
            //FutureTarget会阻塞
            //所以需要在子线程调用
            val file = withContext(Dispatchers.IO) {
                val future = Glide.with(AppContext.instance)
                    .asFile()
                    .load(ResourceUtil.resourceUri(data.icon!!))
                    .submit()
                future.get() // 阻塞 Glide 获取结果
            }


            //将文件拷贝到我们需要的位置
            FileUtils.moveFile(file, targetFile)

            PreferenceUtil.setSplashAd(data)
        } catch (e: Exception) {
            e.printStackTrace()

            //下载失败，使用默认图片
            val defaultInputStream = AppContext.instance.resources.openRawResource(R.raw.moon)
            FileUtils.copyInputStreamToFile(defaultInputStream, targetFile)

            PreferenceUtil.setSplashAd(data)
        }
    }
}